<?php


namespace App\Http\Controllers\Dsc\Controllers;


use App\Http\Controllers\Controller;
use App\Http\Controllers\Dsc\Model\Goods;
use App\Http\Controllers\Dsc\Model\Orderinfo;
use App\Http\Controllers\Dsc\Model\Orderreturn;
use App\Http\Controllers\Dsc\Model\Send;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rules\NotIn;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;

class OrderinfoController extends Controller
{
    public function index()
    {

        $method = $_REQUEST['method'];
        $appkey = $_REQUEST['appkey'];
        $token = $_REQUEST['token'];
        $bizcontent = $_REQUEST['bizcontent'];
        $sign = $_REQUEST['sign'];
        $appSecret = "86426339e6ca4890ae060bc00ce39907";    //appSecret的值通过在菠萝派中申请应用获得
        if (empty($method) || empty($appkey) || empty($token) || empty($bizcontent) || empty($sign)) {
            return response()->json(['code' => '40000', 'message' => 'System Error', 'subcode' => 'GSE.SYSTEM_ERROR', 'submessage' => '公共接口缺少必要参数']);
        }
        $unsign = $appSecret . "appkey" . $appkey . "bizcontent" . $bizcontent . "method" . $method . "token" . $token . $appSecret;
        $newsign = md5(strtolower($unsign));
//       dd($newsign);
//        echo $newsign;
        Log::info('sign'.$newsign);
        if ($sign != $newsign) {
            return response()->json(['code' => '40000', 'message' => 'Logical Error', 'subcode' => 'GSE.VERIFYSIGN_FAILURE', 'submessage' => '签名验证失败']);
        }
        if ($method == "Differ.JH.Business.GetOrder") {
            $request = json_decode($bizcontent, true);
            $PageIndex = $request["PageIndex"] == 0 ? 0 : $request["PageIndex"] - 1;
            $PageSize = $request["PageSize"];
            /**
             * dsc_order_info  ru_id  0 表示自营
             * main_count =0 说明是子订单号
             * 过滤2多件商品的主单号查询出 和只有一件商品的订单
             */
            $where = [
                'ru_id' => 0,//自营
                'main_count' => 0,//子订单和只有一件商品的订单的查询条件
//                'main_order_id' => 0
            ];
            $hanld = DB::connection('mysql2')->table('order_info');
            $hanld = $hanld->where($where)->orWhereNotIn('pay_status', [0]);

            if (!empty($request['PlatOrderNo'])) {
                $PlatOrderNo = $request['PlatOrderNo'];
                $hanld->where('order_sn', '=', $PlatOrderNo);
            }

            if (!empty($request['StartTime'])) {
                $hanld->where('add_time', '>=', strtotime($request['StartTime']))->get();
            }

            if (!empty($request['EndTime'])) {
                $hanld->where('add_time', '<=', strtotime($request['EndTime']));
            }

            $hanld = $hanld->orderByDesc('add_time');
            $select = [
                'order_id',
                'main_order_id',//
                'main_count',
                'order_sn as PlatOrderNo',//订单号
                'add_time',//订单添加时间
                'user_id',
                'order_status as tradeStatus',//订单交易状态
                'pay_status',
                'consignee as receivername',//收货人姓名
                'country',
                'province',
                'district',
                'city',
                'address',
                'shipping_status',//配送状态
                'shipping_fee as postfee',//运费
                'mobile',//电话
                'postscript as customerremark',//订单备注客户的
                'to_buyer as sellerremark',//卖家留言
                'cost_amount as goodsfee',//货款金额
                'goods_amount as totalmoney',//合计应收（针对卖家）
                'money_paid as realpaymoney', //实际支付金额（用户支付金额，已减去优惠金额，开发票给用户时可用此金额）
                'discount as favourablemoney',//订单优惠金额（针对整个订单的优惠）
                'pay_time as paytime',//支付时间
                'invoice_no as logisticno',//物流单号
                'shipping_name as logisticname',//物流名称
//                'discount as '
            ];
            $hanld = $hanld->select($select);

            $numtotalorder = $hanld->count(['order_id']);
            $res = $hanld->offset($PageIndex)->limit($PageSize)->get();
            $res = objectToArray($res);
            foreach ($res as $i => $vv) {

                if ($vv['main_count'] > 0) {
                    unset($res[$i]);
                }
            }

            $Orderinfo = new Orderinfo();
            $result = $Orderinfo->get_orders_data($res);
            $array['code'] = 10000;
            $array['message'] = 'SUCCESS';
            $array['numtotalorder'] = $numtotalorder;
            $array['orders'] = isset($result) ? $result : [];
            return $array;

        } elseif ($method == "Differ.JH.Business.Send") {
            //发货接口
            $request = json_decode($bizcontent, true);
            $data = Send::syncChangesModel($request);
            return CheckRefundSendStatusModel($data);

        } elseif ($method == "Differ.JH.Business.CheckRefundStatus") {
            //查询订单是否有退款接口
            $request = json_decode($bizcontent, true);
            if (!isset($request['PlatOrderNo'])) {
                return response()->json(['code' => '40000', 'message' => 'System Error', 'subcode' => 'GSE.SYSTEM_ERROR', 'submessage' => '缺少平台订单OrderID']);
            }
            $PlatOrderNo = $request['PlatOrderNo'];
            $refundStatus = Orderreturn::getrefundStatus($PlatOrderNo);
            return $refundStatus;
        } elseif ($method == "Differ.JH.Business.DownloadProduct") {
            //商品下载接口
            $request_data = json_decode($bizcontent, true);
            return Goods::getgoodsModel($request_data);
        } elseif ($method == "Differ.JH.Business.SyncStock") {
            //库存同步接口
            $request = json_decode($bizcontent, true);
            if (empty($request["PlatProductID"]) || ($request['Quantity'] < 0)) {
                return response()->json(['code' => '40000', 'message' => 'System Error', 'subcode' => 'GSE.SYSTEM_ERROR', 'submessage' => '缺少平台商品sku编号或库存数量参数不对']);
            }
            //查看是不是有这个商品
            $product = Goods::getproductModel($request['PlatProductID']);
            if ($product == null) {
                return response()->json(['code' => '40000', 'message' => 'System Error', 'subcode' => 'GSE.SYSTEM_ERROR', 'submessage' => "找不到商品编码" . $request['PlatProductID'] . "对应的商品"]);
            }
            //直接根据 goods_sn 更新这个商品goods表里面的主库存
            $update = Goods::syncstockModel($request['PlatProductID'], $request['Quantity']);
            $stock = $request['Quantity'];
            if ($update == 1) {
                return response()->json(['code' => '10000', 'message' => 'SUCCESS', 'Quantity' => $stock]);
            }
        } elseif ($method == "Differ.JH.Business.GetRefund") {
            //货物退款接口
            $result = json_decode($bizcontent, true);
            if (empty($result['BeginTime']) || empty($result['EndTime']) || empty($result['PageIndex']) || empty($result['PageSize'])) {
                return response()->json(['code' => '40000', 'message' => 'System Error', 'subcode' => 'GSE.SYSTEM_ERROR', 'submessage' => '调用参数缺失']);
            }
            $PageIndex = $result["PageIndex"];
            $PageSize = $result["PageSize"];
            $returnOrderList = Orderreturn::getReturnorderList($PageIndex, $PageSize);
            return $returnOrderList;
        } else {
            return response()->json(['code' => '40000', 'message' => 'System Error', 'subcode' => 'GSE.SYSTEM_ERROR', 'submessage' => '调用接口方法名有误，超出可选范围']);
        }


    }

}